<!--
 * @Description: 聊天窗口
 * @Author: liu (1427179517@qq.com)
 * @Date: 2023-05-04 16:46:58
 * @LastEditors: liu (1427179517@qq.com)
 * @LastEditTime: 2023-05-05 14:18:04
 * @FilePath: \jiekuan-app\src\subPages\other\chat.vue
-->
<template>
	<div class="page">
		<div class="page-header">
			<u-navbar title="" :background="nav_background" title-color="#fff" back-icon-color="#fff"
				:border-bottom="false" :height="60">
				<div class="u-flex all-center flex-1 nav_box">
					<image v-if="to.userInfo.icon" :src="to.userInfo.icon" class="avatar u-m-r-15" alt="" />
					<span>{{to.userInfo.nickname}}</span>
				</div>
				<image slot="right" src="../../static/images/setting.png" class="setting_icon u-m-r-40"
					@click="isPopup = true" alt="" />
			</u-navbar>
		</div>
		<div class="page-content u-p-20">
			<div class="hint">
				请勿通过平台进行非法交易，如被举报核实将做封号处理。任何私下交易行 为，请谨慎判断，以防人身或财产损失
			</div>
			<div class="vip_box u-m-t-12 u-flex u-col-center u-row-between">
				<div>
					<div class="u-flex u-col-center">
						<image src="../../static/images/wechat.png" class="wechat_icon u-m-r-18" alt="" />
						<span class="wechat">V*************2</span>
					</div>
					<div class="u-flex u-col-center u-m-t-10">
						<span>升级</span>
						<image src="../../static/images/personal_vip.png" class="vip_icon u-m-r-10 u-m-l-10" alt="" />
						<span class="">免费解锁</span>
					</div>
				</div>
				<div class="open_vip" @click="handleClick({ type: 'vip' })">立即解锁</div>
			</div>
            <scroll-view  class="chat-content" scroll-y="true" :scroll-into-view="scrollIntoView" upper-threshold="-50">
			    <view v-for="(item, index) in list" :key="index">
                    <view  :id="item.key">
                        <div class="time u-m-t-40">{{ item.time }}</div>
                        <div class="u-flex u-col-center u-m-t-10" v-if="item.type === 1">
                            <!-- <image src="" class="img" alt="" /> -->
                            <image class="emojiIcon" :src='item.text'  v-if='item.event=="img"'></image>
                            <div class="u-m-l-18 msg" v-else>{{ item.text }}</div>
                        </div>
                        <div class="u-flex all-center u-m-t-24" v-else-if="item.type === 2">
                            <div class="msg_hint">{{ item.text }}</div>
                        </div>
                        <div class="u-flex flex-end o0l u-m-t-10" v-else-if="item.type === 3">
                            <div class="u-m-r-18 msg msg_right">
                                <image class="emojiIcon" :src='item.text'  v-if='item.event=="img"'></image>
                                <div class="u-m-r-18 msg msg_right" v-else>{{ item.text }}</div>
                            </div>

                            <!-- <image src="" class="img" alt="" /> -->
                        </div>
                    </view>

                </view>
            </scroll-view>
        </div>
		<div class="page-footer">
			<div class="u-flex footer_box">
				<u-input v-model="inputMsg" placeholder="输入消息" class="input_box u-p-l-30" @confirm="handleSend" />
				<image src="../../static/images/chat_smile.png" class="u-m-l-15 icon" alt="" @click="isFaces=true" />
				<image src="../../static/images/chat_add.png" class="u-m-l-20 icon" alt="" @click="handleFile" />
			</div>
		</div>
		<!-- 操作菜单 -->
		<u-popup v-model="isPopup" mode="bottom" safe-area-inset-bottom border-radius="30">
			<view class="pop_box">
				<button class="pop_btn pop_btn_look" @click="handleClick({ type: 'personal' })">查看资料</button>
				<button class="pop_btn u-m-t-20"  @click="handleClick({ type: 'remove' })">拉黑</button>
				<button class="pop_btn u-m-t-20" @click="handleClick({ type: 'feedback' })">举报</button>
				<button class="pop_btn pop_btn_cancel" @click="isPopup = false">取消</button>
			</view>
		</u-popup>

       <!-- <u-popup v-model="isFaces"  mode="bottom" closeable safe-area-inset-bottom border-radius="30">
            <view class="emoji u-flex u-flex-wrap">
                <view style="margin: 6rpx 13rpx;" v-for="(item,index) in emojiItems" v-if="index > 1" @click="emojiAction(item)">
                    <u-image width="60" height="60"  :src="item" :lazy-load="true"></u-image>
                </view>
            </view>
        </u-popup> -->

		<u-popup v-model="isFaces"  mode="bottom" closeable safe-area-inset-bottom border-radius="30">
            <swiper  class="showEmoji" :indicator-dots="true" :autoplay="false" :interval="5000" :duration="1000">
                <block>
                    <swiper-item>
                        <view class="emoji_item">
                            <image v-for="(item, index) in emojiObj.map1" :key="index" :src="'../../../../' + emojiObj.path + item"  @click="emojiAction(index)" :data-emoji="index"></image>
                        </view>
                        <view class="emoji_item">
                            <image v-for="(item, index) in emojiObj.map2" :key="index" :src="'../../../../' +emojiObj.path + item"  @click="emojiAction(index)" :data-emoji="index"></image>
                        </view>
                        <view class="emoji_item">
                            <image v-for="(item, index) in emojiObj.map3" :key="index" :src="'../../../../' +emojiObj.path + item"  @click="emojiAction(index)" :data-emoji="index"></image>
                        </view>
                    </swiper-item>
                </block>
                <block class="second">
                    <swiper-item>
                        <view class="emoji_item">
                            <image v-for="(item, index) in emojiObj.map4" :key="index" :src="'../../../../' +emojiObj.path + item" @click="emojiAction(index)"></image>
                        </view>
                        <view class="emoji_item">
                            <image v-for="(item, index) in emojiObj.map5" :key="index" :src="'../../../../' +emojiObj.path + item"  @click="emojiAction(index)"></image>
                        </view>
                        <view class="emoji_item last_item">
                            <image v-for="(item, index) in emojiObj.map6" :key="index" :src="'../../../../' +emojiObj.path + item" @click="emojiAction(index)"></image>
                        </view>
                    </swiper-item>
                </block>
            </swiper>
        </u-popup>
	</div>
</template>

<script>
	import {
		formatTime
	} from "@/utils/publicMethod"
	export default {
		name: 'Chat', // 页面名称
		components: {}, // 挂载组件
		props: {}, // 组件传值
		data() {
			return {
			    im:{
                    isOpened:false
                },
                scrollIntoView:'',
                nowMessage:{
                    index:0
                }, // 最新记录
				nav_background: {
					background: 'transparent'
				},
				list: [

				], // 信息列表
				value: '', // 消息
				toNickname: '', // 发送到xx手机
				isPopup: false, // 操作弹窗
                isFaces: false, // 表情是否打开
                emojiObj: this.$WebIM.EmojiObj,
                to:{
				    id:this.$route.query.id,
				    user:null,
                    userInfo:{}
                },
				inputMsg:'',
        filePath: '' // 上传的图片
			}
		},
		computed: {}, // 计算机属性 类似与data概念
		watch: {}, // 监控data中数据变化
		created() {

            const {
                user
            } = this.$WebIM.makeAuthMap(this.toNickname)
            this.to.user = user

        }, // 生命周期-创建完成(可以访问当前this实例)
		mounted() {

        }, // 生命周期-挂载完成(可以访问DOM元素)
		methods: {}, // 挂载一些方法
		onLoad(options) {
			this.toNickname = options.n
			console.log('onLoad', options, Date.now())
            this.listen()

		}, // 生命周期回调—监听页面加载
        watch:{
		    im:{
                handler:function(newMessages, oldMessages){
                 this.handleHistory()
                },
                deep:true
            }
        },
		onShow() {

		    console.log('1231223')
            this.apiGetFetchMemberInfo()
        }, // 生命周期回调—监听页面显示
		onReady() {}, // 生命周期回调—监听页面初次渲染完成
		onHide() {}, // 生命周期回调—监听页面隐藏
		onUnload() {}, // 生命周期回调—监听页面卸载
		methods: {
            // 页面点击事件
            handleClick(options) {
                const {
                    type,
                    item,
                    index,
                    query = {
                        id:this.$route.query.id,
                        n:this.$route.query.n,
                    }
                } = options
                switch (type){
                    case 'remove':
                        this.apiPostBlockMember(this.to.id)
                        break;

                    default:
                        this.$jump({
                            name: type,
                            query
                        })
                        break
                }

            },
            // 消息发送
			handleSend(str='') {
				// 发送一条文本消息
				const option = {
					msg: str || this.value,
					to: this.to.user,
					success: (id, serverMsgId) => {
						// 发送成功
						console.log('发送成功', serverMsgId, id)
						const e = this.$WebIM.emojiToImg( str || this.value )
					    const msgMap  = {
							time: formatTime(),
							text:e.text,
							key:`tag_${this.nowMessage.index+=1}`,
							event: 'send',
							type: 3
						}
						if(e.type==1){
							msgMap.event='img'
						}
                        this.list.push(msgMap)
                        this.$nextTick(()=>{
                            this.scrollIntoView = msgMap.key
                        })
					},
					fail: (error) => {
						// 发送失败
						console.log('发送失败', error)
					}
				}
				this.inputMsg = ''
				this.$WebIM.sendMessage(option)
			},
			// 消息处理
			processingMessages(message) {
				const e = this.$WebIM.emojiToImg( message.sourceMsg)
				let text = {
					time: formatTime(parseInt(message.time)),
					text: e.text,
					event: 'receive',
					type: 1
				}
				if(e.type==1){
					text.event='img'
				}
				switch (message.contentsType) {
					case "TEXT":

						break;
				}

				this.list.push(text)
			},
			// 图片发送
			handleFile() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: res => {
						const filePath = res.tempFilePaths[0]
						// 创建FileReader对象并调用readAsDataURL方法
						let reader = new FileReader();
						reader.onload = (e) => {
							let base64Img = e.target.result;
							console.log('base64Img', base64Img);

							// 将base64格式的图片转化为Blob格式
							let arr = base64Img.split(',');
							let mime = arr[0].match(/:(.*?);/)[1];
							let bstr = atob(arr[1]);
							let n = bstr.length;
							let u8arr = new Uint8Array(n);
							while (n--) {
								u8arr[n] = bstr.charCodeAt(n);
							}
							let blob = new Blob([u8arr], {
								type: mime
							});

							// 上传并发送图片消息
							this.filePath = filePath; //用于获取图片信息
							this.$WebIM.uploadAndSend(blob, this.to.user).then(url => {
								const msgMap = {
									time: formatTime(),
									text: url,
									key: `tag_${this.nowMessage.index+=1}`,
									event: 'img',
									type: 3
								}

								this.list.push(msgMap)
								this.$nextTick(() => {
									this.scrollIntoView = msgMap.key
								})
							});
						}

						// 读取文件内容并转化为base64格式
						let file = res.tempFiles[0];
						reader.readAsDataURL(file.slice(0, file.size));
					},
					fail: () => {
						console.log('取消');
					}
				});

			},
			// emoji
			emojiAction(emoji) {
				var str;
				var msglen = this.value.length - 1;

				if (emoji && emoji != "[del]") {
					str = this.value + emoji;
				} else if (emoji == "[del]") {
					let start = this.value.lastIndexOf("[");
					let end = this.value.lastIndexOf("]");
					let len = end - start;

					if (end != -1 && end == msglen && len >= 3 && len <= 4) {
						str = this.value.slice(0, start);
					} else {
						str = this.value.slice(0, msglen);
					}
				}
				// this.value = str;
				this.handleSend(str)
			},
			// 获取历史记录
			handleHistory() {
				const history = this.$WebIM.history({
					targetId: this.to.user,
					chatType: 'singleChat',
					searchDirection: 'up',
					cursor: '-1',
					pageSize: 50,
				})
				history.then(item => {
					const {
						cursor,
						messages
					} = item
					messages.reverse()

					let nowMessage = undefined
					const list = messages.map((m, index) => {
						const e = this.$WebIM.emojiToImg(m.msg)
						let msgMap = {
							time: formatTime(parseInt(m.time)),
							text: e.text,
							key: `tag_${index}`,
							index,
							type: m.from == this.to.user ? 1 : 3,
						}
						if (m.type == 'img') {
							msgMap.event = 'img'
							msgMap.text = m.url
							/* let options = {
								url: m.url,
								headers: {
									'Accept': 'image/*'
								},
								onFileDownloadComplete: (response) => {
									var objectURL = this.$WebIM.utils.parseDownloadResponse
										.call(
											this.$WebIM.conn,
											response
										);
									msgMap.event = 'img'
									msgMap.text = objectURL;
								},
								onFileDownloadError: function() {
									console.log('File down load error.')
								}
							}
							this.$WebIM.utils.download.call(
								this.$WebIM.conn,
								options
							); */

						} else {

						}

						if (e.type == 1) {
							msgMap.event = 'img'
						}
						nowMessage = msgMap
						return msgMap
					})
					console.log('list', list)
					this.list = list
					if (nowMessage != undefined) {
						this.nowMessage = nowMessage
						this.$nextTick(() => {
							this.scrollIntoView = `${nowMessage.key}`
						})
					}
				})
			},
			// listen
			listen() {
				this.$WebIM.conn.listen({
					onOpened: (message) => {
						this.im.isOpened = true
					},
					// 接受消息监听
					onTextMessage: (message) => {
						console.log('接受消息监听onTextMessage====>', message)
						this.processingMessages(message) // 处理收到的消息的函数
					},
					onCustomMessage: (message) => {
						console.log('收到自定义消息onCmdMessage: ', message)
					},
					// 收到自定义消息
					onReceivedMessage: (message) => {
						console.log('onReceivedMessage : ', message)
					},
					onPictureMessage: (message) => {
						// console.log("Location of Picture is ", message);
						console.log(JSON.stringify(message));
						var options = {
							url: message.url
						};
						options.onFileDownloadComplete = function(data) {
							//图片下载成功，需要将data转换成blob，使用objectURL作为img标签的src即可。
							var objectURL = WebIM.utils.parseDownloadResponse.call(taht.$conn, data);
							console.log(objectURL)
						}
						options.onFileDownloadError = function() {
							// 图片下载失败
							console.log('下载失败');
						};
						WebIM.utils.download.call(taht.$conn, options);
						msgShow('receiver', 'img', options.url);
						pushMessageToJson("receiver", "img", options.url);
					}
				})
			},
			// 获取用户信息
			async apiGetFetchMemberInfo() {
				await this.$u.api.GetFetchMemberInfo({
					memberId: this.to.id
				}).then((res) => {
					const {
						data
					} = res
					this.to.userInfo = data
					this.im.isOpened = true
				})
			},
			// 移除黑名单
			apiPostBlockMember(id) {
				this.$u.api.PostBlockMember({
					blockedMemberId: id
				}).then((res) => {
					this.$toast('移除成功')
					this.page = 1
					this.isPopup = false

				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-image: url('http://minio.tianhong.mobi/mall/xiaoq/home_bg.png');
		width: 100%;
		background-size: cover;
		background-repeat: no-repeat;
	}

	.page-header,
	.page-content,
	.page-footer {
		background: transparent;
	}

	.page-content {
		padding-top: 110rpx !important;
	}

	.setting_icon {
		width: 37rpx;
		height: 34rpx;
	}

	.nav_box {
		font-size: 31rpx;
		font-family: Microsoft YaHei UI;
		font-weight: 400;
		color: #ffffff;

		.avatar {
			width: 70rpx;
			height: 70rpx;
			border-radius: 50%;
		}
	}

	.hint {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 90rpx;
		background: #2f2c88;
		font-size: 21rpx;
		font-family: Microsoft YaHei UI;
		font-weight: 400;
		color: #ffffff;
		line-height: 33rpx;
		padding: 18rpx 32rpx;
	}

	.vip_box {
		background-image: url(../../static/images/vipbg.png);
		width: 100%;
		height: 104rpx;
		background-size: cover;
		background-repeat: no-repeat;
		padding: 0 26rpx;
	}

	.wechat_icon {
		width: 40rpx;
		height: 34rpx;
	}

	.vip_icon {
		width: 65rpx;
		height: 22rpx;
	}

	.wechat {
		font-size: 25rpx;
		font-family: Microsoft YaHei UI;
		font-weight: bold;
		color: #c54153;
	}

	.open_vip {
		width: 130rpx;
		height: 45rpx;
		background: #ffdf50;
		border-radius: 23rpx;
		font-size: 21rpx;
		font-family: Microsoft YaHei UI;
		font-weight: 400;
		color: #d7443e;
		text-align: center;
		line-height: 45rpx;
	}
    .chat-content{
        height: calc(100% - 100rpx);
    }
	.time {
		font-size: 25rpx;
		font-family: Microsoft YaHei UI;
		font-weight: 400;
		color: #dcdcdc;
		text-align: center;
	}

	.img {
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
	}

	.msg {
		padding: 20rpx 25rpx;
		background: #2f189e;
		border-radius: 8rpx;
		font-size: 25rpx;
		font-family: Microsoft YaHei UI;
		font-weight: 400;
		color: #ffffff;
	}

	.msg_hint {
		font-size: 21rpx;
		font-family: Microsoft YaHei UI;
		font-weight: 400;
		color: #d7443e;
	}

	.msg_right {
		background: #ffdf50;
		color: #000000;
	}

	.icon {
		width: 60rpx;
		height: 60rpx;
	}

	.footer_box {
		padding: 10rpx 20rpx;
	}

	.input_box {
		background: #ffffff;
		border-radius: 35rpx;
	}

	.pop_box {
		padding: 40rpx 50rpx 35rpx;
	}

	.pop_btn {
		width: 650rpx;
		height: 90rpx;
		background: #fcc307;
		border-radius: 45rpx;
		font-size: 33rpx;
		font-family: Microsoft YaHei UI;
		font-weight: 400;
		color: #000000;
		line-height: 90rpx;
	}

	.pop_btn_look {
		color: #ffffff;
	}

	.pop_btn_cancel {
		color: #ffffff;
		background: #c8c8c8;
		margin-top: 65rpx;
	}

	.emoji {
		padding: 80rpx 30rpx 50rpx;
	}

	.emoji_list {
		margin-top: 30px;
		width: 100%;
		height: 145px;
		background-color: #dddddd;
		padding-top: 10px;
		padding-left: 3%;
		display: none;
	}

	.showEmoji {
		width: 100%;
		height: 145px;
		padding-top: 10px;
		padding-left: 3%;
		display: block;
	}

	.emoji_list image,
	.showEmoji image {
		width: 26px;
		height: 26px;
		margin: 5px 2%;
	}

	.emoji {
		width: 26px;
		height: 26px;
		margin: 0 0;
	}

	.emoji_item {
		display: flex;
		justify-content: space-around;
		margin-right: 20px;
	}

	.last_item {
		justify-content: flex-end !important
	}

	.emojiIcon {
		width: 60rpx;
		height: 60rpx;
	}
</style>
